package kr.bos.Framework.Utils;

import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;

import kr.bos.Define.Key;
import kr.bos.Framework.Logger;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;

/**
 * 어플 용량 줄이기 위해서 모든 그림은 인터넷에서 받아오기로 한다.
 * @author baek - bispro@uracle.co.kr
 * @date 2011. 12. 29.
 */
public class ImageLoader {
	
	public static HashMap<String, Drawable> g_tabDrawable = new HashMap<String, Drawable>();
	
	public synchronized static Drawable getDrawable(String URL) {
		if(URL == null) {
			URL = Key.IMG_URL_KLDP;
		}
		Drawable preDrawn = g_tabDrawable.get(URL);
		if(preDrawn!=null) {
			return preDrawn;
		}
		String prefix = "URL LOAD ["+URL+"] ";
		try {
			Logger.e(prefix+"START..");
			InputStream is = (InputStream) new URL(URL).getContent();
			g_tabDrawable.put(URL, Drawable.createFromStream(is, "IMGCHANN"+Rand.getInstance().nextInt()));
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(g_tabDrawable.get(URL)!=null) {
			Logger.e(prefix+"SUCCEED");
		}else {
			Logger.e(prefix+"FAILED");
			return null;
		}
		
		return g_tabDrawable.get(URL);
	}
	
	public synchronized static Bitmap getBitmap(String URL) {
		return ((BitmapDrawable) getDrawable(URL)).getBitmap();
	}
	
	public synchronized static Bitmap getBitmap(String URL, int dstWidth, int dstHeight) {
		//drawable 사이즈 조정
		Bitmap bitmapOrg = getBitmap(URL);
		int srcWidth = bitmapOrg.getWidth();
		int stcHeight = bitmapOrg.getHeight();
		// calculate the scale
		float scaleWidth = ((float) dstWidth) / srcWidth;
		float scaleHeight = ((float) dstHeight) / stcHeight;
		// create a matrix for the manipulation
		Matrix matrix = new Matrix();
		// resize the bit map
		matrix.postScale(scaleWidth, scaleHeight);
		return Bitmap.createBitmap(bitmapOrg, 0, 0,srcWidth, stcHeight, matrix, true);
	}
	
	public synchronized static Drawable getDrawable(String URL, int dstWidth, int dstHeight) {
		return new BitmapDrawable(getBitmap(URL,dstWidth,dstHeight));
	}
}
